package com.realtyreg.webview.filter;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.security.Principal;

/**
 * Фильтр используется для логирования
 * Created by Petro 24.11.12 19:31
 */
public class LogFilter implements Filter {
    private static final Logger LOG = Logger.getLogger(LogFilter.class);

    public void init(FilterConfig filterConfig) throws ServletException {
    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        boolean isRes = req.getRequestURI().startsWith("/resources/");

        StringBuilder sb = new StringBuilder();
        sb.append(req.getMethod()).append(" запрос: ").append(req.getRequestURI());
        if (StringUtils.isNotEmpty(req.getQueryString()))
            sb.append(" параметры: ").append(req.getQueryString());

        try {
            if (!isRes)
                LOG.info("START: " + sb.toString());
            chain.doFilter(request, response);
        } catch (Exception e) {
            Principal principal = req.getUserPrincipal();
            if (principal != null)
                sb.append(" пользователь: ").append(principal.getName());
            LOG.error("ERROR: " + sb.toString(), e);
        } finally {
            if (!isRes)
                LOG.info("END: " + sb.toString());
        }
    }

    public void destroy() {
    }
}
